﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FantastPlatform.Framework;
using FantastPlatform.Framework.Core;
using FantastPlatform.Framework.Model;
using FantastPlatform.Decision.IService;
using FantastPlatform.Decision.IModel;
using FantastPlatform.Decision.Model;
using FantastPlatform.Framework.IService;
using FantastPlatform.Framework.IModel;
using FantastPlatform.Framework.Common;

namespace FantastPlatform.Decision.UI.Service
{
    public partial class ImportantCaseViewService : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            LoginEmployee = Session["User"] as FantastPlatform.Framework.Model.Employee;
            IImportantCaseService importantCaseService = ServiceFactory.CreateService<IImportantCaseService>();
            ConditionGroup group = new ConditionGroup();
            int totalCount = 0;
            switch (Action)
            {
                case "Add":
                    string data = Data;
                    IImportantCase importantCase = (IImportantCase)JsonToEntity<ImportantCase>(RepairString(data));
                    bool isSendMsg = !string.IsNullOrEmpty(importantCase.IsSendMsg);
                    GetLeaders(importantCase, isSendMsg);
                    if (importantCase.Id == 0)
                    {
                        importantCase.Enable = true;
                        if (LoginEmployee != null)
                        {
                            importantCase.Writer = LoginEmployee;
                            importantCase.CreateDate = DateTime.Now;
                            importantCaseService.Create(importantCase);
                            ReturnSuccessMessage("保存警务信息成功");
                        }
                        else
                        { ReturnErrorMessage("未登陆或数字证书已过期！"); }
                    }
                    else
                    {
                        IImportantCase OldImportantCase = importantCaseService.Get(importantCase.Id);
                        OldImportantCase.ModifyDate = DateTime.Now;
                        OldImportantCase.Name = importantCase.Name;
                        OldImportantCase.Title = importantCase.Title;
                        OldImportantCase.Content = importantCase.Content;
                        OldImportantCase.Persons = importantCase.Persons;
                        importantCaseService.Update(OldImportantCase);
                        ReturnSuccessMessage("更新警务信息成功");
                    }
                    break;
                case "Search":
                    Condition enableCondition = new Condition() { Type = typeof(bool).FullName, Field = "Enable", Value1 = true };
                    group.Conditions.Add(enableCondition);
                    IList<Sort> sorts = new List<Sort>();
                    sorts.Add(new Sort() { Field = "CreateDate", Order = Orders.Desc });
                    IList<IImportantCase> importantCaseList = importantCaseService.Search(group, sorts, PageSize, SelfPage, out totalCount);
                    var obj = from n in importantCaseList
                              select new
                              {
                                  Id = n.Id,
                                  Title = n.Title,
                                  Content = n.Content,
                                  Writer = n.Writer == null ? "" : n.Writer.Name,
                                  Leaders = string.Join(",", (from p in n.Persons
                                                              where p.Enable == true
                                                              select p.Name).ToArray()),
                                  Unread = GetLeadersStatus(n.Id),
                                  CreateDate = n.CreateDate.ToString()
                              };
                    ReturnList(totalCount, obj.ToList());
                    break;
                case "SearchByCondition":
                    string Searchjson = RepairString(Data);
                    importantCase = (IImportantCase)JsonToEntity<MaintainStability>(Searchjson);
                    enableCondition = new Condition() { Type = typeof(bool).FullName, Field = "Enable", Value1 = true };
                    Condition condition1 = new Condition() { Type = typeof(string).FullName, Field = "Name", Value1 = '%' + importantCase.Name + '%', Comparison = Comparisons.Like, Relation = Relations.And };
                    group.Conditions.Add(enableCondition);
                    group.Conditions.Add(condition1);
                    sorts = new List<Sort>();
                    sorts.Add(new Sort() { Field = "CreateDate", Order = Orders.Desc });
                    importantCaseList = importantCaseService.Search(group, sorts, PageSize, SelfPage, out totalCount);
                    obj = from n in importantCaseList
                          select new
                          {
                              Id = n.Id,
                              Title = n.Title,
                              Content = n.Content,
                              Writer = n.Writer == null ? "" : n.Writer.Name,
                              Leaders = string.Join(",", (from p in n.Persons
                                                          where p.Enable == true
                                                          select p.Name).ToArray()),
                              Unread = GetLeadersStatus(n.Id),
                              CreateDate = n.CreateDate.ToString()

                          };
                    var objList = obj.ToList();
                    ReturnList(objList.Count, objList);
                    break;
                case "Get":
                    importantCase = importantCaseService.Get(Id);
                    object objImportantCase = (new
                                     {
                                         Id = importantCase.Id,
                                         Title = importantCase.Title,
                                         Content = importantCase.Content,
                                         Writer = importantCase.Writer.Name,
                                         CreateDate = importantCase.CreateDate.ToString()
                                     });
                    ReturnObj(objImportantCase);
                    break;
                case "Delete":
                    if (string.IsNullOrEmpty(Data))
                    {
                        throw new Exception("传入的警务信息ID为空");
                    }
                    List<int> idList = new List<int>();
                    string[] idStrList = Data.Split(',');
                    foreach (string id in idStrList)
                    {
                        idList.Add(int.Parse(id));
                    }
                    importantCaseService.Delete(idList);
                    ReturnSuccessMessage("删除警务信息成功");
                    break;
                case "GetLeadersByImportantCaseId":
                    IImportantCase ps = importantCaseService.Get(Id);
                    string leaders = string.Join(",", (from p in ps.Persons
                                                       where p.Enable == true
                                                       select p.Code.ToString()).ToArray<string>());
                    ReturnSuccessMessage(leaders);
                    break;
            }
        }
        private string GetLeadersStatus(int Id)
        {
            int totalCount = 0;
            IImportantCasePersonService importantCasePersonService = ServiceFactory.CreateService<IImportantCasePersonService>();
            ConditionGroup conditionGroup = new ConditionGroup();
            conditionGroup.Conditions.Add(new Condition() { Type = typeof(bool).FullName, Field = "Enable", Value1 = true });
            conditionGroup.Conditions.Add(new Condition() { Type = typeof(int).FullName, Value1 = Id, Field = "ImportantCase.Id", Relation = Relations.And });
            IList<IImportantCasePerson> importantCasePersonList = importantCasePersonService.Search(conditionGroup, null, Int32.MaxValue, 1, out totalCount);
            string status = string.Join(",", (from m in importantCasePersonList
                                              where m.Person != null&&m.Receive ==false
                                              select m.Person.Name).ToArray());
            return status;

        }
        private void GetLeaders(IImportantCase importantCase, bool IsSendMsg)
        {
            string[] codes;
            if (!string.IsNullOrEmpty(Request["Leaders"]))
            {
                codes = Request["Leaders"].Split(',');
                if (codes.Length > 0)
                {
                    importantCase.Persons = new List<IEmployee>();
                    foreach (string code in codes)
                    {
                        IEmployeeService service = ServiceFactory.CreateService<IEmployeeService>();
                        IEmployee emp = service.Get(code);
                        if (emp != null)
                        {
                            importantCase.Persons.Add(emp);
                            SendMessage("|07|" + emp.Code);
                            if (IsSendMsg)
                            {
                                string tel = (from c in emp.Contacts
                                              where c.ContactType.Name == "手机"
                                              select c.Value).FirstOrDefault();
                                if (!string.IsNullOrEmpty(tel))
                                {
                                    MessageManager.SendMessage(tel, "您有新的警务信息：" + importantCase.Title + ",请通过决策指挥终端查看详情。（发送人：" + LoginEmployee.Name + ")", LoginEmployee.Code, DateTime.Now);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}